package cn.sll.system.service.impl;

import cn.sll.system.domain.Menu;
import cn.sll.system.service.IMenuService;
import cn.sll.base.service.impl.BaseServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author sll
 * @since 2023-01-03
 */
@Service
public class MenuServiceImpl extends BaseServiceImpl<Menu> implements IMenuService {

    @Override
    public List<Menu>  first() {
        List<Menu>  all = super.findAll();
        List<Menu>  result = new ArrayList<>();
        for (Menu menu : all) {
            if (null == menu.getParentId()){
                result.add(menu);
            }
        }
//      super.findAll().stream().filter(menu->null == menu.getParentId()).collect(Collectors.toList());
        return result;
    }

    @Override
    public List<Menu> tree() {
        List<Menu> result = new ArrayList<>();
        //查询所有数据
        List<Menu> all = super.findAll();
        //将全部数据转换成map key value
        Map<Long, Menu> menuMap = all.stream().collect(Collectors.toMap(Menu::getId, menu -> menu));
        //在内存中组装数据
        for (Menu menu : all) {
            if(null == menu.getParentId()){
                //一级数据
                result.add(menu);
            }else{
                Menu parent = menuMap.get(menu.getParentId());
                parent.getChildren().add(menu);
            }
        }

        return result;
    }
}
